#include <errno.h>
//
#include <machine/param.h>
#include <sys/ipc.h>
#include <sys/shm.h>
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//
#include <signal.h>
//
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
//
#include <sys/stat.h>
//
void *shmdata;
//
void closeShm()
{
  shmdt(shmdata);
}
//
void print_usage()
{
  printf("Usage: shm2file shmid offset size fout\n");
}
//
int main(int argc, char *argv[]){
  // 1 shmid
  // 2 offset
  // 3 size
  // 4 fout

  if(argc<=4){
    print_usage();
    exit(1);
  }

  int shmid=strtol(argv[1],NULL,10);
  size_t offset=strtol(argv[2],NULL,10);
  size_t size=strtol(argv[3],NULL,10);
  char *data;

  shmdata =  shmat ( shmid, ( void * ) 0, 0 );
  if(shmdata==(void *)-1){
    perror("shmat");
    exit(1);
  }

  signal(SIGINT,closeShm);
  signal(SIGTERM,closeShm);

  data = shmdata + offset;

  int d=open(argv[4],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP);
  if(d==-1){
    perror("open");
    exit(1);
  }

  ssize_t ws=write(d, data, size);
  close(d);
  closeShm();

  if(ws==size) exit(0);
  exit(2);
}
